/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Copyright (c) 2017-2022 Fraunhofer IOSB (Author: Andreas Ebner)
 * Copyright (c) 2019 Kalycito Infotech Private Limited
 * Copyright (c) 2021 Fraunhofer IOSB (Author: Jan Hermes)
 * Copyright (c) 2022 Siemens AG (Author: Thomas Fischer)
 * Copyright (c) 2022 Linutronix GmbH (Author: Muddasir Shakil)
 */

#ifndef UA_SERVER_PUBSUB_H
#define UA_SERVER_PUBSUB_H

#include <open62541/common.h>
#include <open62541/util.h>
#include <open62541/client.h>
#include <open62541/plugin/securitypolicy.h>
#include <open62541/plugin/eventloop.h>

_UA_BEGIN_DECLS

#ifdef UA_ENABLE_PUBSUB

/**
 * .. _pubsub:
 *
 * PubSub
 * ======
 *
 * In PubSub the participating OPC UA Applications take their roles as
 * Publishers and Subscribers. Publishers are the sources of data, while
 * Subscribers consume that data. Communication in PubSub is message-based.
 * Publishers send messages to a Message Oriented Middleware, without knowledge
 * of what, if any, Subscribers there may be. Similarly, Subscribers express
 * interest in specific types of data, and process messages that contain this
 * data, without knowledge of what Publishers there are.
 *
 * Message Oriented Middleware is software or hardware infrastructure that
 * supports sending and receiving messages between distributed systems. OPC UA
 * PubSub supports two different Message Oriented Middleware variants, namely
 * the broker-less form and broker-based form. A broker-less form is where the
 * Message Oriented Middleware is the network infrastructure that is able to
 * route datagram-based messages. Subscribers and Publishers use datagram
 * protocols like UDP. In a broker-based form, the core component of the Message
 * Oriented Middleware is a message Broker. Subscribers and Publishers use
 * standard messaging protocols like AMQP or MQTT to communicate with the
 * Broker.
 *
 * This makes PubSub suitable for applications where location independence
 * and/or scalability are required.
 *
 * The Publish/Subscribe (PubSub) extension for OPC UA enables fast and
 * efficient 1:m communication. The PubSub extension is protocol agnostic and
 * can be used with broker based protocols like MQTT and AMQP or brokerless
 * implementations like UDP-Multicasting.
 *
 * The configuration model for PubSub uses the following components: */

typedef enum  {
    UA_PUBSUB_COMPONENT_CONNECTION,
    UA_PUBSUB_COMPONENT_WRITERGROUP,
    UA_PUBSUB_COMPONENT_DATASETWRITER,
    UA_PUBSUB_COMPONENT_READERGROUP,
    UA_PUBSUB_COMPONENT_DATASETREADER
} UA_PubSubComponentEnumType;

/**
 * The open62541 PubSub API uses the following scheme:
 *
 * 1. Create a configuration for the needed PubSub element.
 *
 * 2. Call the add[element] function and pass in the configuration.
 *
 * 3. The add[element] function returns the unique nodeId of the internally created element.
 *
 * Take a look on the PubSub Tutorials for more details about the API usage::
 *
 *  +-----------+
 *  | UA_Server |
 *  +-----------+
 *   |    |
 *   |    |
 *   |    |
 *   |    |  +----------------------+
 *   |    +--> UA_PubSubConnection  |  UA_Server_addPubSubConnection
 *   |       +----------------------+
 *   |        |    |
 *   |        |    |    +----------------+
 *   |        |    +----> UA_WriterGroup |  UA_PubSubConnection_addWriterGroup
 *   |        |         +----------------+
 *   |        |              |
 *   |        |              |    +------------------+
 *   |        |              +----> UA_DataSetWriter |  UA_WriterGroup_addDataSetWriter     +-+
 *   |        |                   +------------------+                                        |
 *   |        |                                                                               |
 *   |        |         +----------------+                                                    | r
 *   |        +---------> UA_ReaderGroup |    UA_PubSubConnection_addReaderGroup              | e
 *   |                  +----------------+                                                    | f
 *   |                       |                                                                |
 *   |                       |    +------------------+                                        |
 *   |                       +----> UA_DataSetReader |  UA_ReaderGroup_addDataSetReader       |
 *   |                            +------------------+                                        |
 *   |                                 |                                                      |
 *   |                                 |    +----------------------+                          |
 *   |                                 +----> UA_SubscribedDataSet |                          |
 *   |                                      +----------------------+                          |
 *   |                                           |                                            |
 *   |                                           |    +----------------------------+          |
 *   |                                           +----> UA_TargetVariablesDataType |          |
 *   |                                           |    +----------------------------+          |
 *   |                                           |                                            |
 *   |                                           |    +------------------------------------+  |
 *   |                                           +----> UA_SubscribedDataSetMirrorDataType |  |
 *   |                                                +------------------------------------+  |
 *   |                                                                                        |
 *   |       +---------------------------+                                                    |
 *   +-------> UA_PubSubPublishedDataSet |  UA_Server_addPublishedDataSet                   <-+
 *           +---------------------------+
 *                 |
 *                 |    +-----------------+
 *                 +----> UA_DataSetField |  UA_PublishedDataSet_addDataSetField
 *                      +-----------------+
 *
 * PubSub Information Model Representation
 * ---------------------------------------
 * .. _pubsub_informationmodel:
 *
 * The complete PubSub configuration is available inside the information model.
 * The entry point is the node 'PublishSubscribe', located under the Server
 * node.
 * The standard defines for PubSub no new Service set. The configuration can
 * optionally be done over methods inside the information model.
 * The information model representation of the current PubSub configuration is
 * generated automatically. This feature can be enabled/disabled by changing the
 * UA_ENABLE_PUBSUB_INFORMATIONMODEL option.
 *
 * Connections
 * -----------
 * The PubSub connections are the abstraction between the concrete transport protocol
 * and the PubSub functionality. It is possible to create multiple connections with
 * different transport protocols at runtime.
 */

/* Valid PublisherId types from Part 14 */
typedef enum {
    UA_PUBLISHERIDTYPE_BYTE   = 0,
    UA_PUBLISHERIDTYPE_UINT16 = 1,
    UA_PUBLISHERIDTYPE_UINT32 = 2,
    UA_PUBLISHERIDTYPE_UINT64 = 3,
    UA_PUBLISHERIDTYPE_STRING = 4
} UA_PublisherIdType;

/* Publisher Id
    Valid types are defined in Part 14, 7.2.2.2.2 NetworkMessage Layout:

    Bit range 0-2: PublisherId Type
    000 The PublisherId is of DataType Byte This is the default value if ExtendedFlags1 is omitted
    001 The PublisherId is of DataType UInt16
    010 The PublisherId is of DataType UInt32
    011 The PublisherId is of DataType UInt64
    100 The PublisherId is of DataType String
*/
typedef union {
    UA_Byte byte;
    UA_UInt16 uint16;
    UA_UInt32 uint32;
    UA_UInt64 uint64;
    UA_String string;
} UA_PublisherId;

/* \brief OPC UA PubSub 连接配置结构体  */
typedef struct {
    UA_String name;                           /* 当前 PubSub 连接名称 */
    UA_Boolean enabled;                       /* 此连接在创建后是否立即启用 */
    UA_PublisherIdType publisherIdType;       /* 指定 publisherId 字段中数据的数据类型 */
    UA_PublisherId publisherId;               /* 发布此数据的发布者（Publisher）的唯一 ID */
    UA_String transportProfileUri;            /* 一个 URI 字符串，指明此连接使用的传输协议配置文件 */
    UA_Variant address;                       /* 包含连接的网络地址信息。其具体数据类型取决于 transportProfileUri */
    UA_KeyValueMap connectionProperties;      /* 存储与此连接相关的额外配置属性 */
    UA_Variant connectionTransportSettings;   /* 传输层特定的配置参数。其具体数据类型和内容取决于 transportProfileUri */

    UA_EventLoop *eventLoop;                  /* 使用外部的事件循环，为 NULL 则使用服务器的事件循环
                                               * 传播到与连接关联的 ReaderGroup/WriterGroup */
} UA_PubSubConnectionConfig;

#ifdef UA_ENABLE_PUBSUB_MONITORING

typedef enum {
    UA_PUBSUB_MONITORING_MESSAGE_RECEIVE_TIMEOUT
    // extend as needed
} UA_PubSubMonitoringType;

/* PubSub monitoring interface */
typedef struct {
    UA_StatusCode (*createMonitoring)(UA_Server *server, UA_NodeId Id,
                                      UA_PubSubComponentEnumType eComponentType,
                                      UA_PubSubMonitoringType eMonitoringType,
                                      void *data, UA_ServerCallback callback);
    UA_StatusCode (*startMonitoring)(UA_Server *server, UA_NodeId Id,
                                     UA_PubSubComponentEnumType eComponentType,
                                     UA_PubSubMonitoringType eMonitoringType, void *data);
    UA_StatusCode (*stopMonitoring)(UA_Server *server, UA_NodeId Id,
                                    UA_PubSubComponentEnumType eComponentType,
                                    UA_PubSubMonitoringType eMonitoringType, void *data);
    UA_StatusCode (*updateMonitoringInterval)(UA_Server *server, UA_NodeId Id,
                                              UA_PubSubComponentEnumType eComponentType,
                                              UA_PubSubMonitoringType eMonitoringType,
                                              void *data);
    UA_StatusCode (*deleteMonitoring)(UA_Server *server, UA_NodeId Id,
                                      UA_PubSubComponentEnumType eComponentType,
                                      UA_PubSubMonitoringType eMonitoringType, void *data);
} UA_PubSubMonitoringInterface;

#endif /* UA_ENABLE_PUBSUB_MONITORING */

/* General PubSub configuration */
struct UA_PubSubConfiguration {
    /* Callback for PubSub component state changes: If provided this callback
     * informs the application about PubSub component state changes. E.g. state
     * change from operational to error in case of a DataSetReader
     * MessageReceiveTimeout. The status code provides additional
     * information. */
    void (*stateChangeCallback)(UA_Server *server, UA_NodeId *id,
                                UA_PubSubState state, UA_StatusCode status);

    UA_Boolean enableDeltaFrames;

#ifdef UA_ENABLE_PUBSUB_INFORMATIONMODEL
    UA_Boolean enableInformationModelMethods;
#endif

#ifdef UA_ENABLE_PUBSUB_ENCRYPTION
    /* PubSub security policies */
    size_t securityPoliciesSize;
    UA_PubSubSecurityPolicy *securityPolicies;
#endif

#ifdef UA_ENABLE_PUBSUB_MONITORING
    UA_PubSubMonitoringInterface monitoringInterface;
#endif
};

/**
 * \brief 向指定服务器添加一个新的 PubSub 连接并将其打开
 *
 * @param server               要添加连接的服务器
 * @param connectionConfig     新添加连接的配置
 * @param connectionIdentifier 如果不为 NULL，将被设置为新添加连接的标识符
 *
 * @return 如果连接成功添加则返回 UA_STATUSCODE_GOOD，否则返回错误代码
 */
UA_StatusCode UA_EXPORT UA_THREADSAFE UA_Server_addPubSubConnection(UA_Server *server,
                                                                    const UA_PubSubConnectionConfig *connectionConfig,
                                                                    UA_NodeId *connectionIdentifier);

/* Returns a deep copy of the config */
UA_StatusCode UA_EXPORT UA_THREADSAFE
UA_Server_getPubSubConnectionConfig(UA_Server *server,
                                    const UA_NodeId connection,
                                    UA_PubSubConnectionConfig *config);

/* Remove Connection, identified by the NodeId. Deletion of Connection
 * removes all contained WriterGroups and Writers. */
UA_StatusCode UA_EXPORT UA_THREADSAFE
UA_Server_removePubSubConnection(UA_Server *server, const UA_NodeId connection);

/**
 * PublishedDataSets
 * -----------------
 * The PublishedDataSets (PDS) are containers for the published information. The
 * PDS contain the published variables and meta information. The metadata is
 * commonly autogenerated or given as constant argument as part of the template
 * functions. The template functions are standard defined and intended for
 * configuration tools. You should normally create an empty PDS and call the
 * functions to add new fields. */

/* The UA_PUBSUB_DATASET_PUBLISHEDITEMS has currently no additional members and
 * thus no dedicated config structure. */

/* \brief 发布数据集类型 */
typedef enum {
    UA_PUBSUB_DATASET_PUBLISHEDITEMS,            /* 表示普通的发布项数据集，包含一组数据项（如变量值）的集合，用于常规数据发布 */
    UA_PUBSUB_DATASET_PUBLISHEDEVENTS,           /* 表示发布事件数据集，用于发布事件通知（如警报、状态变化等），而非常规数据 */
    UA_PUBSUB_DATASET_PUBLISHEDITEMS_TEMPLATE,   /* 表示发布项数据集的模板，模板定义了数据集的结构（如字段、数据类型），可在运行时动态生成实际数据集 */
    UA_PUBSUB_DATASET_PUBLISHEDEVENTS_TEMPLATE,  /* 表示发布事件数据集的模板，类似项模板，但专用于事件数据结构的定义 */
} UA_PublishedDataSetType;

typedef struct {
    UA_DataSetMetaDataType metaData;
    size_t variablesToAddSize;
    UA_PublishedVariableDataType *variablesToAdd;
} UA_PublishedDataItemsTemplateConfig;

typedef struct {
    UA_NodeId eventNotfier;
    UA_ContentFilter filter;
} UA_PublishedEventConfig;

typedef struct {
    UA_DataSetMetaDataType metaData;
    UA_NodeId eventNotfier;
    size_t selectedFieldsSize;
    UA_SimpleAttributeOperand *selectedFields;
    UA_ContentFilter filter;
} UA_PublishedEventTemplateConfig;

/* Configuration structure for PublishedDataSet */
typedef struct {
    UA_String name;
    UA_PublishedDataSetType publishedDataSetType;
    union {
        /* The UA_PUBSUB_DATASET_PUBLISHEDITEMS has currently no additional members
         * and thus no dedicated config structure.*/
        UA_PublishedDataItemsTemplateConfig itemsTemplate;
        UA_PublishedEventConfig event;
        UA_PublishedEventTemplateConfig eventTemplate;
    } config;
} UA_PublishedDataSetConfig;

void UA_EXPORT
UA_PublishedDataSetConfig_clear(UA_PublishedDataSetConfig *pdsConfig);

typedef struct {
    UA_StatusCode addResult;
    size_t fieldAddResultsSize;
    UA_StatusCode *fieldAddResults;
    UA_ConfigurationVersionDataType configurationVersion;
} UA_AddPublishedDataSetResult;

UA_EXPORT UA_AddPublishedDataSetResult UA_THREADSAFE UA_Server_addPublishedDataSet(UA_Server *server,
                                                                                   const UA_PublishedDataSetConfig *publishedDataSetConfig,
                                                                                   UA_NodeId *pdsIdentifier);

/* Returns a deep copy of the config */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_getPublishedDataSetConfig(UA_Server *server, const UA_NodeId pds,
                                    UA_PublishedDataSetConfig *config);

/* Returns a deep copy of the DataSetMetaData for an specific PDS */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_getPublishedDataSetMetaData(UA_Server *server, const UA_NodeId pds,
                                      UA_DataSetMetaDataType *metaData);

/* Remove PublishedDataSet, identified by the NodeId. Deletion of PDS removes
 * all contained and linked PDS Fields. Connected WriterGroups will be also
 * removed. */
UA_StatusCode UA_EXPORT UA_THREADSAFE
UA_Server_removePublishedDataSet(UA_Server *server, const UA_NodeId pds);

/**
 * DataSetFields
 * -------------
 * The description of published variables is named DataSetField. Each
 * DataSetField contains the selection of one information model node. The
 * DataSetField has additional parameters for the publishing, sampling and error
 * handling process. */

/* \brief 数据集变量配置结构体 */
typedef struct{
    UA_ConfigurationVersionDataType configurationVersion;  /* 这个字段的配置版本 */
    UA_String fieldNameAlias;                              /* 该字段在发布的 DataSet 中的别名 */
    UA_Boolean promotedField;                              /* 提升字段标志。如果设置为 true，表示这个字段应该被 “提升” 到 DataSet 的顶层 */
    UA_PublishedVariableDataType publishParameters;        /* 核心发布参数。这个结构体定义了如何读取和发布这个变量的值 */

    /* non std. field */
    struct {
        UA_Boolean rtFieldSourceEnabled;                   /* 实时字段源使能 */
        /* If the rtInformationModelNode is set, the nodeid in publishParameter must point
         * to a node with external data source backend defined
         * */
        UA_Boolean rtInformationModelNode;
        //TODO -> decide if suppress C++ warnings and use 'UA_DataValue * * const staticValueSource;'
        UA_DataValue ** staticValueSource;
    } rtValueSource;
    UA_UInt32 maxStringLength;

} UA_DataSetVariableConfig;

/* \brief PubSub 数据集字段类型 */
typedef enum {
    UA_PUBSUB_DATASETFIELD_VARIABLE,   /* 变量类型 */
    UA_PUBSUB_DATASETFIELD_EVENT       /* 事件 */
} UA_DataSetFieldType;

/* \brief 数据集字段配置结构体 */
typedef struct {
    UA_DataSetFieldType dataSetFieldType;     /* 数据集字段类型 */
    union {
        /* events need other config later */
        UA_DataSetVariableConfig variable;    /* 数据集字段变量配置 */
    } field;
} UA_DataSetFieldConfig;

void UA_EXPORT
UA_DataSetFieldConfig_clear(UA_DataSetFieldConfig *dataSetFieldConfig);

typedef struct {
    UA_StatusCode result;
    UA_ConfigurationVersionDataType configurationVersion;
} UA_DataSetFieldResult;

UA_EXPORT UA_DataSetFieldResult UA_THREADSAFE UA_Server_addDataSetField(UA_Server *server,
                                                                        const UA_NodeId publishedDataSet,
                                                                        const UA_DataSetFieldConfig *fieldConfig,
                                                                        UA_NodeId *fieldIdentifier);

/* Returns a deep copy of the config */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_getDataSetFieldConfig(UA_Server *server, const UA_NodeId dsf,
                                UA_DataSetFieldConfig *config);

UA_EXPORT UA_DataSetFieldResult UA_THREADSAFE
UA_Server_removeDataSetField(UA_Server *server, const UA_NodeId dsf);

/**
 * Custom Callback Implementation
 * ------------------------------
 * The user can use his own callback implementation for publishing
 * and subscribing. The user must take care of the callback to call for
 * every publishing or subscibing interval */

typedef struct {
    /* User's callback implementation. The user configured base time and timer policy
     * will be provided as an argument to this callback so that the user can
     * implement his callback (thread) considering base time and timer policies */
    UA_StatusCode (*addCustomCallback)(UA_Server *server, UA_NodeId identifier,
                                       UA_ServerCallback callback,
                                       void *data, UA_Double interval_ms,
                                       UA_DateTime *baseTime, UA_TimerPolicy timerPolicy,
                                       UA_UInt64 *callbackId);

    UA_StatusCode (*changeCustomCallback)(UA_Server *server, UA_NodeId identifier,
                                          UA_UInt64 callbackId, UA_Double interval_ms,
                                          UA_DateTime *baseTime, UA_TimerPolicy timerPolicy);

    void (*removeCustomCallback)(UA_Server *server, UA_NodeId identifier, UA_UInt64 callbackId);

} UA_PubSub_CallbackLifecycle;

/**
 * WriterGroup
 * -----------
 * All WriterGroups are created within a PubSubConnection and automatically
 * deleted if the connection is removed. The WriterGroup is primary used as
 * container for :ref:`dsw` and network message settings. The WriterGroup can be
 * imagined as producer of the network messages. The creation of network
 * messages is controlled by parameters like the publish interval, which is e.g.
 * contained in the WriterGroup. */

/* \brief PubSub 通信中数据集消息可以使用的编码格式 */
typedef enum {
    UA_PUBSUB_ENCODING_UADP = 0,    /* UA 数据协议（UA Data Protocol），这是 OPC UA PubSub 专用且推荐的二进制编码格式 */
    UA_PUBSUB_ENCODING_JSON = 1,    /* JavaScript 对象表示法（JSON） */
    UA_PUBSUB_ENCODING_BINARY = 2   /* OPC UA 二进制编码，通常用于 OPC UA 客户端/服务器通信 */
} UA_PubSubEncodingType;

/**
 * WriterGroup
 * -----------
 * The message publishing can be configured for realtime requirements. The RT-levels
 * go along with different requirements. The below listed levels can be configured:
 *
 * UA_PUBSUB_RT_NONE
 *    No realtime-specific configuration.
 *
 * UA_PUBSUB_RT_DIRECT_VALUE_ACCESS
 *    All PublishedDataSets need to point to a variable with a
 *    ``UA_VALUEBACKENDTYPE_EXTERNAL`` value backend. The value backend gets
 *    cached when the configuration is frozen. No lookup of the variable from
 *    the information is performed afterwards. This enables also big data
 *    structures to be updated atomically with a compare-and-switch operation on
 *    the ``UA_DataValue`` double-pointer in the backend.
 *
 * UA_PUBSUB_RT_FIXED_SIZE
 *    Validate that the message constains only fields with a known size.
 *    Then the message fields have fixed offsets that are known ahead of time.
 *
 * UA_PUBSUB_RT_DETERMINISTIC
 *    Both direct-access and fixed-size is being used. The server pre-allocates
 *    buffers when the configuration is frozen and uses only memcpy operations
 *    to update the PubSub network messages for sending.
 *
 * WARNING! For hard real time requirements the underlying system must be
 * RT-capable. Also note that each PubSubConnection can have a dedicated
 * EventLoop. That way normal client/server operations can run independently
 * from PubSub. The double-pointer in the ``UA_VALUEBACKENDTYPE_EXTERNAL`` value
 * backend allows avoid race-condition with non-blocking atomic operations. */

/* \brief  PubSub 通信中实时性等级 */
typedef enum {
    UA_PUBSUB_RT_NONE = 0,                  /* 无实时性要求 */
    UA_PUBSUB_RT_DIRECT_VALUE_ACCESS = 1,   /* 直接值访问，这个级别关注于减少数据访问的开销 */
    UA_PUBSUB_RT_FIXED_SIZE = 2,            /* 固定大小，这个级别关注于消息大小的可预测性 */
    UA_PUBSUB_RT_DETERMINISTIC = 3,         /* 确定性，这是最高级别的实时性要求，旨在实现可预测且极低的延迟和抖动 */
} UA_PubSubRTLevel;

/* \brief WriterGroup 配置结构体 */
typedef struct {
    UA_String name;                                        /* 该 WriterGroup 的名称 */
    UA_Boolean enabled;                                    /* 指示该 WriterGroup 是否启用 */
    UA_UInt16 writerGroupId;                               /* 该 WriterGroup 的唯一标识符（ID） */
    UA_Duration publishingInterval;                        /* 发布周期，即每隔多长时间发布一次数据（单位毫秒） */
    UA_Double keepAliveTime;                               /* 保活时间（Keep-Alive Time），单位秒
                                                            * 用途: 即使没有新数据更新，也会定期发送一条“保活”消息，通知订阅者该 WriterGroup 仍然活跃 */
    UA_Byte priority;                                      /* 消息的优先级 */
    UA_ExtensionObject transportSettings;                  /* 传输层配置参数，具体格式取决于所使用的传输协议（如 UDP、MQTT、Ethernet 等） */
    UA_ExtensionObject messageSettings;                    /* 消息编码格式的设置 */
    UA_KeyValueMap groupProperties;                        /* 一个键值对映射，用于存储自定义的配置属性 */
    UA_PubSubEncodingType encodingMimeType;                /* 指定数据编码格式的 MIME 类型 */
    UA_PubSub_CallbackLifecycle pubsubManagerCallback;     /* Pub/Sub 管理器的生命周期回调函数 */
    UA_UInt16 maxEncapsulatedDataSetMessageCount;          /* 一个网络消息中最多封装的 DataSetMessage 数量 */
    /* 非标准字段 */
    UA_PubSubRTLevel rtLevel;                              /* 实时性级别（Real-Time Level），用于指示该 WriterGroup 对实时性的要求 */

    /* 如果配置了安全策略（SecurityPolicy）且安全模式（securityMode）设置得当，则消息将
     * 被加密。对称密钥属于运行时信息，必须通过 UA_Server_setWriterGroupEncryptionKey 函数
     * 进行设置 */
    UA_MessageSecurityMode securityMode;                   /* 安全模式，决定是否加密和签名 */
#ifdef UA_ENABLE_PUBSUB_ENCRYPTION
    UA_PubSubSecurityPolicy *securityPolicy;               /* 安全策略 */
    UA_String securityGroupId;
#endif
} UA_WriterGroupConfig;

void UA_EXPORT UA_WriterGroupConfig_clear(UA_WriterGroupConfig *writerGroupConfig);

/**
 * \brief 添加一个新的 WriterGroup 到已存在的连接中
 */
UA_EXPORT UA_StatusCode UA_THREADSAFE UA_Server_addWriterGroup(UA_Server *server, const UA_NodeId connection,
                                                               const UA_WriterGroupConfig *writerGroupConfig,
                                                               UA_NodeId *writerGroupIdentifier);

/* Returns a deep copy of the config */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_getWriterGroupConfig(UA_Server *server, const UA_NodeId writerGroup,
                               UA_WriterGroupConfig *config);

UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_updateWriterGroupConfig(UA_Server *server, UA_NodeId writerGroupIdentifier,
                                  const UA_WriterGroupConfig *config);

/* Get state of WriterGroup */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_WriterGroup_getState(UA_Server *server, UA_NodeId writerGroupIdentifier,
                               UA_PubSubState *state);

UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_WriterGroup_publish(UA_Server *server, const UA_NodeId writerGroupIdentifier);

UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_WriterGroup_lastPublishTimestamp(UA_Server *server, const UA_NodeId writerGroupId,
                                    UA_DateTime *timestamp);

UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_removeWriterGroup(UA_Server *server, const UA_NodeId writerGroup);

UA_EXPORT UA_StatusCode UA_THREADSAFE UA_Server_freezeWriterGroupConfiguration(UA_Server *server, const UA_NodeId writerGroup);

UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_unfreezeWriterGroupConfiguration(UA_Server *server, const UA_NodeId writerGroup);

UA_EXPORT UA_StatusCode UA_THREADSAFE UA_Server_setWriterGroupOperational(UA_Server *server, const UA_NodeId writerGroup);

UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_setWriterGroupDisabled(UA_Server *server, const UA_NodeId writerGroup);

#ifdef UA_ENABLE_PUBSUB_ENCRYPTION
/* Set the group key for the message encryption */
UA_StatusCode UA_EXPORT UA_THREADSAFE
UA_Server_setWriterGroupEncryptionKeys(UA_Server *server, const UA_NodeId writerGroup,
                                       UA_UInt32 securityTokenId,
                                       const UA_ByteString signingKey,
                                       const UA_ByteString encryptingKey,
                                       const UA_ByteString keyNonce);
#endif

/**
 * .. _dsw:
 *
 * DataSetWriter
 * -------------
 * The DataSetWriters are the glue between the WriterGroups and the
 * PublishedDataSets. The DataSetWriter contain configuration parameters and
 * flags which influence the creation of DataSet messages. These messages are
 * encapsulated inside the network message. The DataSetWriter must be linked
 * with an existing PublishedDataSet and be contained within a WriterGroup. */

/* \brief DataSetWriter 配置结构体 */
typedef struct {
    UA_String name;                                       /* DataSetWriter 的名称 */
    UA_UInt16 dataSetWriterId;                            /* DataSetWriter 的唯一标识符 */
    UA_DataSetFieldContentMask dataSetFieldContentMask;   /* 定义在序列化数据集字段时，需要包含哪些元数据信息 */
    UA_UInt32 keyFrameCount;                              /* 定义关键帧（KeyFrame 或 NetworkMessage）的发送频率 */
    UA_ExtensionObject messageSettings;                   /* 包含与消息格式相关的特定设置 */
    UA_ExtensionObject transportSettings;                 /* 包含与底层传输协议相关的特定设置 */
    UA_String dataSetName;                                /* 该 DataSetWriter 所关联的数据集（DataSet）的名称 */
    UA_KeyValueMap dataSetWriterProperties;               /* 提供一个扩展机制，用于包含自定义或供应商特定的属性 */
} UA_DataSetWriterConfig;

void UA_EXPORT
UA_DataSetWriterConfig_clear(UA_DataSetWriterConfig *pdsConfig);

/**
 * \brief 将一个新的 DataSetWriter 添加到现有的 WriterGroup 中。
 *        在创建 DataSetWriter 时，必须将其与一个 PublishedDataSet 关联
 *
 *        第 14 部分，7.1.5.2.1 节规定：PublishedDataSet 与 DataSetWriter 之间的
 *        链接应在创建 DataSetWriterType 实例时建立。
 */
UA_EXPORT UA_StatusCode UA_THREADSAFE UA_Server_addDataSetWriter(UA_Server *server,
                                                                 const UA_NodeId writerGroup, const UA_NodeId dataSet,
                                                                 const UA_DataSetWriterConfig *dataSetWriterConfig,
                                                                 UA_NodeId *writerIdentifier);

/* Returns a deep copy of the config */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_getDataSetWriterConfig(UA_Server *server, const UA_NodeId dsw,
                                 UA_DataSetWriterConfig *config);

/* Get state of DataSetWriter */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_DataSetWriter_getState(UA_Server *server, UA_NodeId dataSetWriterIdentifier,
                                 UA_PubSubState *state);

UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_removeDataSetWriter(UA_Server *server, const UA_NodeId dsw);

/**
 * SubscribedDataSet
 * -----------------
 * SubscribedDataSet describes the processing of the received DataSet.
 * SubscribedDataSet defines which field in the DataSet is mapped to which
 * Variable in the OPC UA Application. SubscribedDataSet has two sub-types
 * called the TargetVariablesType and SubscribedDataSetMirrorType.
 * SubscribedDataSetMirrorType is currently not supported. SubscribedDataSet is
 * set to TargetVariablesType and then the list of target Variables are created
 * in the Subscriber AddressSpace. TargetVariables are a list of variables that
 * are to be added in the Subscriber AddressSpace. It defines a list of Variable
 * mappings between received DataSet fields and added Variables in the
 * Subscriber AddressSpace. */

/* \brief SubscribedDataSetDataType 定义 */
typedef enum {
    UA_PUBSUB_SDS_TARGET,         /* 目标模式, SubscribedDataSet 中的字段值会直接写入（映射到）配置好的目标 OPC UA Variable 节点中 */
    UA_PUBSUB_SDS_MIRROR          /* 镜像模式, SubscribedDataSet 的数据不会直接更新目标 Variable 节点的值属性
                                   * 相反，它会创建一个本地数据的 “镜像” 副本。原始的、通过 PubSub 接收到的数据被完整地保存在一个内部的、独立的数据结构中 */
} UA_SubscribedDataSetEnumType;

typedef struct {
    /* Standard-defined FieldTargetDataType */
    UA_FieldTargetDataType targetVariable;

    /* If realtime-handling is required, set this pointer non-NULL and it will be used
     * to memcpy the value instead of using the Write service.
     * If the beforeWrite method pointer is set, it will be called before a memcpy update
     * to the value.
     * If the afterWrite method pointer is set, it will be called after a memcpy update
     * to the value. */
    UA_DataValue **externalDataValue;
    void *targetVariableContext; /* user-defined pointer */
    void (*beforeWrite)(UA_Server *server,
                        const UA_NodeId *readerIdentifier,
                        const UA_NodeId *readerGroupIdentifier,
                        const UA_NodeId *targetVariableIdentifier,
                        void *targetVariableContext,
                        UA_DataValue **externalDataValue);
    void (*afterWrite)(UA_Server *server,
                       const UA_NodeId *readerIdentifier,
                       const UA_NodeId *readerGroupIdentifier,
                       const UA_NodeId *targetVariableIdentifier,
                       void *targetVariableContext,
                       UA_DataValue **externalDataValue);
} UA_FieldTargetVariable;

typedef struct {
    size_t targetVariablesSize;
    UA_FieldTargetVariable *targetVariables;
} UA_TargetVariables;

/* Return Status Code after creating TargetVariables in Subscriber AddressSpace */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_DataSetReader_createTargetVariables(UA_Server *server,
                                              UA_NodeId dataSetReaderIdentifier,
                                              size_t targetVariablesSize,
                                              const UA_FieldTargetVariable *targetVariables);

/* To Do:Implementation of SubscribedDataSetMirrorType
 * UA_StatusCode
 * A_PubSubDataSetReader_createDataSetMirror(UA_Server *server, UA_NodeId dataSetReaderIdentifier,
 * UA_SubscribedDataSetMirrorDataType* mirror) */

/**
 * DataSetReader
 * -------------
 * DataSetReader can receive NetworkMessages with the DataSetMessage
 * of interest sent by the Publisher. DataSetReaders represent
 * the configuration necessary to receive and process DataSetMessages
 * on the Subscriber side. DataSetReader must be linked with a
 * SubscribedDataSet and be contained within a ReaderGroup. */

typedef enum {
    UA_PUBSUB_RT_UNKNOWN = 0,
    UA_PUBSUB_RT_VARIANT = 1,
    UA_PUBSUB_RT_DATA_VALUE = 2,
    UA_PUBSUB_RT_RAW = 4,
} UA_PubSubRtEncoding;

/* \brief DataSetReader 是 OPC UA PubSub 中的一个关键组件，它运行在订阅端（Subscriber），负责：
 *        从网络接收由 Publisher 发送的网络消息，它负责
 *        - 解码这些消息。
 *        - 从消息中提取出特定的 DataSet（数据集）。
 *        - 将提取出的数据映射到本地变量（通常是服务器的地址空间节点） */
typedef struct {
    UA_String name;                                       /* DataSetReader 名称 */
    UA_Variant publisherId;                               /* 标识发送该 DataSet 的发布者 */
    UA_UInt16 writerGroupId;                              /* 标识发布端的 WriterGroup，一个发布端可以有多个 WriterGroup，
                                                           * 每个 Group 可以独立地发布不同频率或不同内容的网络消息
                                                           * DataSetReader 通过此 ID 匹配特定的 WriterGroup */
    UA_UInt16 dataSetWriterId;                            /* 标识 WriterGroup 内部的 DataSetWriter，一个 WriterGroup 可以包含
                                                           * 多个 DataSetWriter，每个 Writer 负责发布一个特定的数据集。DataSetReader
                                                           * 使用此 ID 来精确地选择它要接收的数据集 */
    UA_DataSetMetaDataType dataSetMetaData;               /* 包含了关于所期望接收的数据集的元数据信息 */
    UA_DataSetFieldContentMask dataSetFieldContentMask;   /* 定义了在接收的数据集消息中，哪些附加信息应该被包含在每个字段（Field）中 */
    UA_Double messageReceiveTimeout;                      /* 指定一个超时时间（秒），如果在这个时间内没有收到任何来自指定 Publisher/WriterGroup
                                                           * 的网络消息，DataSetReader 可能会触发超时事件 */
    UA_ExtensionObject messageSettings;                   /* 包含与消息编码和解析相关的特定设置 */
    UA_ExtensionObject transportSettings;                 /* 包含与底层传输协议相关的特定设置 */
    UA_SubscribedDataSetEnumType subscribedDataSetType;   /* 指定接收到的数据集数据将如何被处理和映 */
    /* TODO UA_SubscribedDataSetMirrorDataType subscribedDataSetMirror */
    union {
        UA_TargetVariables subscribedDataSetTarget;       /* 根据 subscribedDataSetType 的值，选择不同的数据处理方式 */
        // UA_SubscribedDataSetMirrorDataType subscribedDataSetMirror;
    } subscribedDataSet;
    /* non std. fields */
    UA_String linkedStandaloneSubscribedDataSetName;
    UA_PubSubRtEncoding expectedEncoding;                 /* 指定了期望的 实时（Real-Time）编码格式，这影响了数据在传输过程
                                                           * 中的打包效率和解析速度，常用于需要低延迟的场景。 */
} UA_DataSetReaderConfig;

/* Copy the configuration of DataSetReader */
UA_EXPORT UA_StatusCode
UA_DataSetReaderConfig_copy(const UA_DataSetReaderConfig *src,
                            UA_DataSetReaderConfig *dst);

/* Clear the configuration of a DataSetReader */
UA_EXPORT void
UA_DataSetReaderConfig_clear(UA_DataSetReaderConfig *cfg);

/* Update configuration to the DataSetReader */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_DataSetReader_updateConfig(UA_Server *server, UA_NodeId dataSetReaderIdentifier,
                                     UA_NodeId readerGroupIdentifier,
                                     const UA_DataSetReaderConfig *config);

/* Get the configuration (copy) of the DataSetReader */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_DataSetReader_getConfig(UA_Server *server, UA_NodeId dataSetReaderIdentifier,
                                  UA_DataSetReaderConfig *config);

/* Get state of DataSetReader */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_DataSetReader_getState(UA_Server *server, UA_NodeId dataSetReaderIdentifier,
                                 UA_PubSubState *state);

typedef struct {
    UA_String name;
    UA_SubscribedDataSetEnumType subscribedDataSetType;
    union {
        /* datasetmirror is currently not implemented */
        UA_TargetVariablesDataType target;
    } subscribedDataSet;
    UA_DataSetMetaDataType dataSetMetaData;
    UA_Boolean isConnected;
} UA_StandaloneSubscribedDataSetConfig;

void
UA_StandaloneSubscribedDataSetConfig_clear(UA_StandaloneSubscribedDataSetConfig *sdsConfig);

UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_addStandaloneSubscribedDataSet(UA_Server *server,
                               const UA_StandaloneSubscribedDataSetConfig *subscribedDataSetConfig,
                               UA_NodeId *sdsIdentifier);

/* Remove StandaloneSubscribedDataSet, identified by the NodeId. */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_removeStandaloneSubscribedDataSet(UA_Server *server, const UA_NodeId sds);

/**
 * ReaderGroup
 * -----------
 *
 * ReaderGroup is used to group a list of DataSetReaders. All ReaderGroups are
 * created within a PubSubConnection and automatically deleted if the connection
 * is removed. All network message related filters are only available in the
 * DataSetReader.
 *
 * The RT-levels go along with different requirements. The below listed levels
 * can be configured for a ReaderGroup.
 *
 * - UA_PUBSUB_RT_NONE: RT applied to this level
 * - PUBSUB_CONFIG_FASTPATH_FIXED_OFFSETS: Extends PubSub RT functionality and
 *   implements fast path message decoding in the Subscriber. Uses a buffered
 *   network message and only decodes the necessary offsets stored in an offset
 *   buffer. */

/* \brief ReaderGroup 配置结构体 */
typedef struct {
    UA_String name;                           /* ReaderGroup 指定一个名称。 */

    UA_PubSubRTLevel rtLevel;                 /* PubSub 实时等级 */
    UA_KeyValueMap groupProperties;           /* 个键值对映射，用于存储与这个 ReaderGroup 相关的特定于传输或实现的扩展属性 */
    UA_PubSubEncodingType encodingMimeType;   /* 指定该 ReaderGroup 期望接收的 DataSetMessage 的编码格式 */
    UA_ExtensionObject transportSettings;     /* 一个 扩展对象，用于封装特定传输协议的详细配置参数 */

    /* 如果配置了安全策略（SecurityPolicy）并且安全模式（securityMode）相应设置，
     * 则消息将被解密。对称密钥是运行时信息，必须通过 UA_Server_setReaderGroupEncryptionKey 进行设置 */
    UA_MessageSecurityMode securityMode;      /* 指定该 ReaderGroup 的安全模式 */
#ifdef UA_ENABLE_PUBSUB_ENCRYPTION
    UA_PubSubSecurityPolicy *securityPolicy;
    UA_String securityGroupId;
#endif
} UA_ReaderGroupConfig;

void UA_EXPORT
UA_ReaderGroupConfig_clear(UA_ReaderGroupConfig *readerGroupConfig);

/**
 * \brief 添加 DataSetReader 到 ReaderGroup 中
 */
UA_EXPORT UA_StatusCode UA_THREADSAFE UA_Server_addDataSetReader(UA_Server *server, UA_NodeId readerGroupIdentifier,
                                                                 const UA_DataSetReaderConfig *dataSetReaderConfig,
                                                                 UA_NodeId *readerIdentifier);

/* Remove DataSetReader from ReaderGroup */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_removeDataSetReader(UA_Server *server, UA_NodeId readerIdentifier);

/* To Do: Update Configuration of ReaderGroup
 * UA_StatusCode UA_EXPORT
 * UA_Server_ReaderGroup_updateConfig(UA_Server *server, UA_NodeId readerGroupIdentifier,
 *                                    const UA_ReaderGroupConfig *config);
 */

/* Get configuraiton of ReaderGroup */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_ReaderGroup_getConfig(UA_Server *server, UA_NodeId readerGroupIdentifier,
                                UA_ReaderGroupConfig *config);

/* Get state of ReaderGroup */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_ReaderGroup_getState(UA_Server *server, UA_NodeId readerGroupIdentifier,
                               UA_PubSubState *state);

/**
 * \brief 添加 ReaderGroup 到已创建的连接中
 */
UA_EXPORT UA_StatusCode UA_THREADSAFE UA_Server_addReaderGroup(UA_Server *server, UA_NodeId connectionIdentifier,
                                                               const UA_ReaderGroupConfig *readerGroupConfig,
                                                               UA_NodeId *readerGroupIdentifier);

/* Remove ReaderGroup from connection */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_removeReaderGroup(UA_Server *server, UA_NodeId groupIdentifier);

UA_EXPORT UA_StatusCode UA_THREADSAFE UA_Server_freezeReaderGroupConfiguration(UA_Server *server, const UA_NodeId readerGroupId);

UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_unfreezeReaderGroupConfiguration(UA_Server *server, const UA_NodeId readerGroupId);

UA_EXPORT UA_StatusCode UA_THREADSAFE UA_Server_setReaderGroupOperational(UA_Server *server, const UA_NodeId readerGroupId);

UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_setReaderGroupDisabled(UA_Server *server, const UA_NodeId readerGroupId);

#ifdef UA_ENABLE_PUBSUB_ENCRYPTION
/* Set the group key for the message encryption */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_setReaderGroupEncryptionKeys(UA_Server *server, UA_NodeId readerGroup,
                                       UA_UInt32 securityTokenId,
                                       UA_ByteString signingKey,
                                       UA_ByteString encryptingKey,
                                       UA_ByteString keyNonce);
#endif

#ifdef UA_ENABLE_PUBSUB_SKS

/**
 * SecurityGroup
 * -------------
 *
 * A SecurityGroup is an abstraction that represents the message security settings and
 * security keys for a subset of NetworkMessages exchanged between Publishers and
 * Subscribers. The SecurityGroup objects are created on a Security Key Service (SKS). The
 * SKS manages the access to the keys based on the role permission for a user assigned to
 * a SecurityGroup Object. A SecurityGroup is identified with a unique identifier called
 * the SecurityGroupId. It is unique within the SKS.
 *
 * .. note:: The access to the SecurityGroup and therefore the securitykeys managed by SKS
 *           requires management of Roles and Permissions in the SKS. The Role Permission
 *           model is not supported at the time of writing. However, the access control plugin can
 *           be used to create and manage role permission on SecurityGroup object.
 */

typedef struct {
    UA_String securityGroupName;
    UA_Duration keyLifeTime;
    UA_String securityPolicyUri;
    UA_UInt32 maxFutureKeyCount;
    UA_UInt32 maxPastKeyCount;
} UA_SecurityGroupConfig;

/**
 * @brief Creates a SecurityGroup object and add it to the list in PubSub Manager. If the
 * information model is enabled then the SecurityGroup object Node is also created in the
 * server. A keyStorage with initial list of keys is created with a SecurityGroup. A
 * callback is added to new SecurityGroup which updates the keys periodically at each
 * KeyLifeTime expire.
 *
 * @param server The server instance
 * @param securityGroupFolderNodeId The parent node of the SecurityGroup. It must be of
 * SecurityGroupFolderType
 * @param securityGroupConfig The security settings of a SecurityGroup
 * @param securityGroupNodeId The output nodeId of the new SecurityGroup
 * @return UA_StatusCode The return status code
 */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_addSecurityGroup(UA_Server *server, UA_NodeId securityGroupFolderNodeId,
                           const UA_SecurityGroupConfig *securityGroupConfig,
                           UA_NodeId *securityGroupNodeId);

/**
 * @brief Removes the SecurityGroup from PubSub Manager. It removes the KeyStorage
 * associated with the SecurityGroup from the server.
 *
 * @param server The server instance
 * @param securityGroup The nodeId of the securityGroup to be removed
 * @return UA_StatusCode The returned status code.
 */
UA_EXPORT UA_StatusCode UA_THREADSAFE
UA_Server_removeSecurityGroup(UA_Server *server, const UA_NodeId securityGroup);

/**
 * @brief This is a repeated callback which is triggered on each iteration of SKS Pull request.
 * The server uses this callback to notify user about the status of current Pull request iteration.
 * The period is calculated based on the KeylifeTime of specified in the SecurityGroup object node on
 * the SKS server.
 *
 * @param server The server instance managing the publisher/subscriber.
 * @param sksPullRequestStatus The current status of sks pull request.
 * @param context The pointer to user defined data passed to this callback.
 */
typedef void
(*UA_Server_sksPullRequestCallback)(UA_Server *server, UA_StatusCode sksPullRequestStatus, void* context);

/**
 * @brief Sets the SKS client config used to call the GetSecurityKeys Method on SKS and get the
 * initial set of keys for a SecurityGroupId and adds timedCallback for the next GetSecurityKeys
 * method Call. This uses async Client API for SKS Pull request. The SKS Client instance is created and destroyed at
 * runtime on each iteration of SKS Pull request by the server. The key Rollover mechanism will check if the new
 * keys are needed then it will call the getSecurityKeys Method on SKS Server. At the end of SKS Pull request
 * iteration, the sks client will be deleted by a delayed callback (in next server iteration).
 *
 * @note It is be called before setting Reader/Writer Group into Operational because this also allocates
 * a channel context for the pubsub security policy.
 *
 * @note the stateCallback of sksClientConfig will be overwritten by an internal callback.
 *
 * @param server the server instance
 * @param clientConfig holds the required configuration to make encrypted connection with
 * SKS Server. The input client config takes the lifecycle as long as SKS request are made.
 * It is deleted with its plugins when the server is deleted or the last Reader/Writer
 * Group of the securityGroupId is deleted. The input config is copied to an internal
 * config object and the content of input config object will be reset to zero.
 * @param endpointUrl holds the endpointUrl of the SKS server
 * @param securityGroupId the SecurityGroupId of the securityGroup on SKS and
 * reader/writergroups
 * @param callback the user defined callback to notify the user about the status of SKS
 * Pull request.
 * @param context passed to the callback function
 * @return UA_StatusCode the retuned status
 */
UA_StatusCode UA_EXPORT
UA_Server_setSksClient(UA_Server *server, UA_String securityGroupId,
                       UA_ClientConfig *clientConfig, const char *endpointUrl,
                       UA_Server_sksPullRequestCallback callback, void *context);

#endif /* UA_ENABLE_PUBSUB_SKS */

#endif /* UA_ENABLE_PUBSUB */

_UA_END_DECLS

#endif /* UA_SERVER_PUBSUB_H */
